<!--
/**
* @description **设备管理
* @author mingd
* @date 2020-05-14
*/
-->
<template>
  <div class="equipmentManagement">
    <section class="equipmentManagement-tree">
      <a-input-search style="margin-bottom: 8px"
                      allowClear
                      ref="searchEntRef"
                      placeholder="请输入企业名称"
                      @change="searchEnt" />
      <!-- 左侧树状图 -->
      <div class="tree-content">
        <a-spin :spinning="leftTreeLoading"
                wrapperClassName="tree-spin">
          <a-tree :show-line="true"
                  :key="treeKey"
                  :load-data="onLoadTreeData"
                  :show-icon="true"
                  :tree-data="treeData"
                  :replace-fields="replaceFields"
                  @select="selectLine">
            <template slot="custom-folder"
                      slot-scope="{ listWorkshop, expanded }">
              <a-icon :type="expanded ? 'folder-open' : 'folder'"
                      theme="filled"/>
            </template>
            <template slot="customEntinfo"
                      slot-scope="{ name, entinfoId }">
              <span :title="name">{{name.length > 8? (name.slice(0, 8)+'...'): name}}</span>
              <a-icon type="plus-circle"
                      class="tree-custom-item"
                      @click.stop="addEquipment({entinfoId})" />
            </template>
            <template slot="customWorkshop"
                      slot-scope="{ name, entinfoId,  workshopId }">
              <span :title="name">{{name.length > 5? (name.slice(0, 5)+'...'): name}}</span>
              <a-icon type="edit"
                      class="tree-custom-item"
                      @click.stop="editWorkShop({name, entinfoId, workshopId})" />
              <a-popconfirm title="确定删除？" @confirm="delWorkShop(workshopId, entinfoId)">
                <a-icon type="minus-circle"
                        class="tree-custom-item"
                        @click.stop="" />
              </a-popconfirm>
            </template>
          </a-tree>
        </a-spin>
      </div>
    </section>
    <div class="index-right-box">
      <!-- 右侧查询 -->
      <a-form-model ref="searchForm"
                    class="index-search-form-model"
                    layout="inline"
                    :model="searchForm"
      >
        <a-form-model-item label="污染分类"
                           prop="polluteType">
            <a-select v-model="searchForm.polluteType"
                      allowClear
                      placeholder="请选择污染分类">
                <a-select-option v-for="(item,index) in polluteTypes"
                           :key="index"
                           :value="item.value"> {{item.name}}</a-select-option>
            </a-select>
        </a-form-model-item>
        <a-form-model-item label="设备名称"
                           prop="equipmentName">
          <a-input
            allowClear
            placeholder="请输入设备名称"
            v-model="searchForm.equipmentName"></a-input>
        </a-form-model-item>
        <a-form-model-item class="top-widget-btn">
          <a-button type="primary"
                    icon="search"
                    shape="round"
                    @click="queryListBycondition">查询</a-button>
          <a-button icon="retweet"
                    shape="round"
                    @click="resetList">重置</a-button>
        </a-form-model-item>
      </a-form-model>
      <!-- 顶部控件 -->
      <section class="table-list">
        <!-- 操作按钮 -->
        <div class="table-opt-btns">
          <a-button type="primary"
                    icon="plus"
                    @click="addEquipmentManagement"
                    :disabled="!currSelTreeNode.workshopId">新增</a-button>
        </div>
        <!-- 表格操作 -->
        <!-- :rowSelection="{selectedRowKeys: selectedRowKeys,onChange: selectedRowChange}" -->
        <a-table :columns="columns"
                 :dataSource="tableData"
                 :customRow="tableCustomRow"
                 bordered
                 rowKey="id"
                 :loading="tableLoading"
                 @change="tableChange"
                 :pagination="pagination">
          <span slot="customPolluteType"
                slot-scope="text">
            {{(polluteTypes.filter(({name, value}) => value === text) && polluteTypes.filter(({name, value}) => value === text)[0] && polluteTypes.filter(({name, value}) => value === text)[0].name) || text}}
          </span>
          <span slot="customEquipmentType"
                slot-scope="text">
            {{(equipmentTypes.filter(({name, value}) => value === text) && equipmentTypes.filter(({name, value}) => value === text)[0] && equipmentTypes.filter(({name, value}) => value === text)[0].name) || text}}
          </span>
          <div slot="operation"
               slot-scope="text,record,index"
               class="tabe-button">
            <a-button size="small"
                      type="primary"
                      icon="edit"
                      @click="editData(text, record, index)">编辑</a-button>
            <!-- <a-button size="small"
                      type="primary"
            @click="viewData(text, record, index)">查看 </a-button>-->
            <a-button size="small"
                      type="danger"
                      icon="close"
                      @click="delData(text, record, index)">删除</a-button>
          </div>
        </a-table>
      </section>
    </div>
    <!-- 表格 -->
    <!-- 新增编辑设备 -->
    <operate-form :operateVisible="operateVisible"
                  :optType="optType"
                  :confirmLoading.sync="confirmLoading"
                  :operateData="operateData"
                  @handleSubmit="submitData"
                  @handleVisible="handleOperateTableVisible"></operate-form>
    <!-- 新增编辑生产线 -->
    <a-modal :title="entFormTitle"
             :visible="entFormVisible"
             :confirm-loading="entFormConfirmLoading"
             @ok="handleOkToEntForm"
             okText="提交"
             :okButtonProps="{props:{icon:'save'}}"
             :cancelButtonProps="{props:{icon:'close-circle'}}"
             @cancel="closeEntModal">
      <a-form-model ref="refEntForm"
                    :model="entform"
                    :rules="entformRules"
                    :label-col="{span:6}"
                    :wrapper-col="{span:18}">
        <a-form-model-item label="生产线名称"
                           prop="productionLineName">
          <a-input v-model="entform.productionLineName"
                   placeholder="请输入生产线名称"
          ></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { getDictData } from '@/request/api/common'
import { post } from '@/request/http'
import {
  getWorkshopByPage,
  deleteWorkshop,
  addWorkshop,
  updateWorkshop,
  getHnEntinfoAndWorkshop,
  updateByPrimaryKeySelective,
  insertSelective,
  deleteByPrimaryKey,
  queryHnEntinfoList,
  queryHnWorkshopList
} from '@/request/api/enterpriseInformationManagement/equipmentManagement'
import { regexConstants, validators } from '@/utils/validate'
import { getFinalPageNo } from '@/utils/index'
import { equipmentManagementColumns } from '@/utils/columns'
import {
  FormModel,
  Tree,
  Input,
  Button,
  Table,
  Icon,
  Modal,
  Spin,
  Select,
  Popconfirm
  // Upload
} from 'ant-design-vue'
import OperateForm from './components/OperateForm'
const { Search } = Input
export default {
  name: 'equipmentManagement',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    AButton: Button,
    ATable: Table,
    OperateForm: OperateForm,
    ATree: Tree,
    AIcon: Icon,
    AModal: Modal,
    ASpin: Spin,
    AInputSearch: Search,
    ASelect: Select,
    ASelectOption: Select.Option,
    APopconfirm: Popconfirm
    // AUpload: Upload
  },
  computed: {
    // 是否有选中项
    isSelecte () {
      return this.selectedRowKeys.length > 0
    }
  },
  data () {
    return {
      options: [],
      treeData: [],
      replaceFields: {
        children: 'listWorkshop',
        title: 'name',
        key: 'customId'
      },
      // 表单
      searchForm: {
        polluteType: undefined,
        equipmentName: ''
      },
      // 角色表头
      columns: equipmentManagementColumns,
      // 表数据
      tableData: [],
      // 表格选中数据
      selectedRowKeys: [],
      // 表格loading
      tableLoading: false,
      // 分页配置
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页显示数量
        showQuickJumper: true, // 跳转
        showSizeChanger: true, // 显示改变每页数量
        total: 0, // 总数
        pageSizeOptions: ['10', '15', '20', '25'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      // 是否打开新增和编辑抽屉
      operateVisible: false,
      // 新增编辑
      optType: 'add',
      // 新增和编辑抽屉数据
      operateData: {
        equipmentName: '',
        equipmentId: '',
        equipmentType: '1',
        polluteType: '1',
        workshopId: '',
        threshold: ''
      },
      confirmLoading: false,
      industryCategoryConst: [],
      areaConst: [],
      // 当前选中树节点id
      currSelTreeNode: {},
      // 生产线增添modal
      entformRules: {
        productionLineName: [
          { required: true, message: '请输入生产线名称', trigger: 'change' },
          {
            pattern: regexConstants.name,
            validator: validators.validate,
            message: '只能输入汉字、数字、字母',
            trigger: 'change'
          }
        ]
      },
      entform: {
        productionLineName: '',
        workshopId: '',
        entinfoId: ''
      },
      entFormTitle: '',
      entFormVisible: false,
      entFormConfirmLoading: false,
      // 树loading
      leftTreeLoading: false,
      // 污染分类 字典
      polluteTypes: [],
      // 设备状态 字典
      equipmentTypes: [],
      // 树形搜索框防抖timer
      treeSearchTimer: null,
      // 树key
      treeKey: '',
      // 上传loading
      upLoading: false
    }
  },
  created () {
    this.getDictDataList()
    this.queryListByPage()
    // this.getHnEntinfoAndWorkshop()
    this.queryHnEntinfoList({
      entinfoName: ''
    })
    // for (let i = 0; i < 8000; i++) {
    //   this.treeData.push({
    //     name: '企业' + i,
    //     id: i,
    //     entinfoId: i,
    //     scopedSlots: {
    //       title: 'customEntinfo'
    //     }
    //   })
    // }
  },
  methods: {
    // table自定义事件
    tableCustomRow (record) {
      return {
        on: { // 事件
          dblclick: (event) => {
            this.optType = 'view'
            this.operateData = Object.assign({}, { id: record.id })
            this.operateVisible = true
          }
        }
      }
    },
    // 生产线表单提交
    handleOkToEntForm () {
      this.$refs.refEntForm.validate(valid => {
        if (valid) {
          this.entFormConfirmLoading = true
          const {
            entinfoId,
            productionLineName,
            workshopId
          } = this.entform
          const isEdit = !!workshopId
          if (!isEdit) { // 新增
            insertSelective({
              id: '',
              entinfoId,
              productionLineName
            }).then(({
              code,
              msg
            }) => {
              this.entFormConfirmLoading = false
              if (code === '0') {
                this.entFormVisible = false
                this.resetEntForm()
                this.$message.success('新增成功!')
                this.updateHnWorkshopList(entinfoId)
              }
            }).catch(() => {
              this.entFormConfirmLoading = false
            })
          } else { // 编辑
            updateByPrimaryKeySelective({
              id: workshopId,
              entinfoId,
              productionLineName,
              workshopId
            }).then(({
              code,
              msg
            }) => {
              this.entFormConfirmLoading = false
              if (code === '0') {
                this.entFormVisible = false
                this.resetEntForm()
                this.$message.success('修改成功!')
                this.updateHnWorkshopList(entinfoId)
              }
            }).catch(() => {
              this.entFormConfirmLoading = false
            })
          }
        } else {
          this.$message.error('请完善信息！')
          return false
        }
      })
    },
    // 重置生产线表单
    resetEntForm () {
      this.$refs.refEntForm.resetFields()
      this.entform.productionLineName = ''
      this.entform.workshopId = ''
      this.entform.entinfoId = ''
    },
    closeEntModal () {
      this.entFormVisible = false
      this.resetEntForm()
    },
    // 增加生产线
    addEquipment ({
      entinfoId
    }) {
      this.entFormVisible = true
      this.entFormTitle = '新增生产线'
      this.entform.entinfoId = entinfoId
      this.entform.productionLineName = ''
    },
    // 编辑生产线
    editWorkShop ({
      name,
      workshopId,
      entinfoId
    }) {
      this.entFormVisible = true
      this.entform.productionLineName = name
      this.entform.workshopId = workshopId
      this.entform.entinfoId = entinfoId
      this.entFormTitle = '编辑生产线'
    },
    // 删除生产线
    delWorkShop (workshopId, entinfoId) {
      deleteByPrimaryKey({
        id: workshopId
      }).then(({
        code,
        msg
      }) => {
        if (code === '0') {
          this.$message.success('删除成功')
          this.updateHnWorkshopList(entinfoId)
          // 删除成功的生产线 刚好是选中的生产线 则表格查询全部数据并重置currSelTreeNode
          if (workshopId === this.currSelTreeNode.workshopId) {
            this.currSelTreeNode = {
            }
            this.pagination.current = 1
            this.queryDataByPage(this.searchForm)
          }
        }
      }).catch(() => {
      })
    },
    // 点击树状图
    selectLine (selectedKeys, info) {
      this.pagination.current = 1
      if (!selectedKeys.length) {
        this.currSelTreeNode = {}
        this.queryDataByPage(this.searchForm)
        return
      }
      const {
        selectedNodes
      } = info
      const {
        workshopId,
        entinfoId,
        type,
        entinfoName
      } = selectedNodes[0].data.props
      this.currSelTreeNode = {
        workshopId,
        entinfoId,
        type,
        entinfoName
      }
      this.queryDataByPage(this.searchForm)
    },
    // 懒加载和更新企业生产线后执行
    // 将当前企业 无生产线置为文件状态 有生产线置为文件夹状态
    // 利用对象浅拷贝
    formatterCurrEntCustomIcon (currEnt) {
      const { listWorkshop, scopedSlots } = currEnt
      if (!listWorkshop || !listWorkshop.length) {
        currEnt.class = 'tree-last-node'
        delete scopedSlots.icon
      } else {
        scopedSlots.icon = 'custom-folder'
        delete currEnt.class
      }
    },
    // 懒加载查询生产线
    onLoadTreeData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        const currEnt = treeNode.dataRef
        // 浅拷贝
        this.updateHnWorkshopList(currEnt.entinfoId, currEnt).then(() => {
          resolve()
        })
      })
    },
    // 更新企业生产线
    async updateHnWorkshopList (entinfoId, currEnt) {
      await queryHnWorkshopList({
        entinfoId
      }).then((res) => {
        if (res.code === '0') {
          const treeData = this.treeData
          if (!currEnt) {
            currEnt = treeData.find(({ id }) => {
              return entinfoId === id
            })
          }
          res.data.forEach((workshop) => {
            workshop.type = 'workshop'
            workshop.entinfoName = currEnt.name
            workshop.workshopId = workshop.id
            workshop.name = workshop.productionLineName
            workshop.customId = entinfoId + '-' + workshop.id
            workshop.scopedSlots = {
              title: 'customWorkshop'
            }
            workshop.isLeaf = true
            workshop.class = 'tree-last-node'
          })
          currEnt.listWorkshop = [...res.data]
          this.formatterCurrEntCustomIcon(currEnt)
          this.treeData = [...treeData]
        }
      })
    },
    // 获取所有企业
    queryHnEntinfoList ({ entinfoName }) {
      this.leftTreeLoading = true
      queryHnEntinfoList({ name: entinfoName }).then((res) => {
        if (res.code === '0') {
          res.data.forEach((ent) => {
            ent.entinfoId = ent.id
            ent.entinfoName = ent.name
            ent.customId = ent.id
            ent.type = 'ent'
            ent.scopedSlots = {
              title: 'customEntinfo',
              icon: 'custom-folder' // 启用懒加载初始必为文件夹状态
            }
          })
          this.treeKey = new Date().getTime()
          this.treeData = [...res.data.slice(0, 100)] // 默认只显示100家
          this.leftTreeLoading = false
        }
      })
    },
    // 按名称搜索企业
    searchEnt (e) {
      const value = e.target.value
      clearTimeout(this.treeSearchTimer)
      this.treeSearchTimer = setTimeout(() => {
        this.queryHnEntinfoList({
          entinfoName: value
        })
        // 重置table 和 当前点击的树节点
        this.currSelTreeNode = {
        }
        this.pagination.current = 1
        this.queryDataByPage(this.searchForm)
      }, 1000)
    },
    // 格式化所有企业及对应的生产线信息
    formatterTreeData (resData) {
      resData.forEach((ent) => {
        ent.entinfoId = ent.id
        ent.entinfoName = ent.name
        ent.customId = ent.id
        ent.type = 'ent'
        ent.scopedSlots = {
          title: 'customEntinfo',
          icon: 'custom-folder'
        }
        if (ent.listWorkshop && ent.listWorkshop.length) {
          ent.listWorkshop.forEach((workshop) => {
            workshop.type = 'workshop'
            workshop.entinfoName = ent.name
            workshop.workshopId = workshop.id
            workshop.name = workshop.productionLineName
            workshop.customId = ent.id + '-' + workshop.id
            workshop.scopedSlots = {
              title: 'customWorkshop'
            }
            workshop.class = 'tree-last-node'
          })
        }
      })
      return resData.slice(0, 100)
    },
    // 查询所有企业及对应的生产线信息
    getHnEntinfoAndWorkshop () {
      this.treeData = this.formatterTreeData(this.treeData)
      this.leftTreeLoading = true
      getHnEntinfoAndWorkshop({}).then((res) => {
        if (res.code === '0') {
          this.treeData = this.formatterTreeData(res.data)
          this.leftTreeLoading = false
        }
      })
    },
    // 获取数据字典
    async getDictDataList () {
      const params = 'w-001,Y-001,Y-0B-008,Y-002'
      await getDictData(params).then(res => {
        if (res.code === '0') {
          const data = res.data
          // 行业门类
          this.industryCategoryConst = data['w-001']
          this.areaConst = data['Y-001']
          this.polluteTypes = data['Y-0B-008']
          this.equipmentTypes = data['Y-002']
        }
      })
    },
    // 查询列表数据
    queryDataByPage (query) {
      this.tableLoading = true
      if (this.currSelTreeNode.type === 'ent') {
        query = {
          ...query,
          workshopId: '',
          entinfoId: this.currSelTreeNode.entinfoId
        }
      } else if (this.currSelTreeNode.type === 'workshop') {
        query = {
          ...query,
          workshopId: this.currSelTreeNode.workshopId,
          entinfoId: this.currSelTreeNode.entinfoId
        }
      }
      const params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        param: query
      }
      getWorkshopByPage(params)
        .then(res => {
          this.tableLoading = false
          if (res.code === '0') {
            this.tableData = res.data.list
            this.pagination.total = res.data.total
          } else {
            this.tableDdata = []
            this.pagination.total = 0
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    // 默认查询
    queryListByPage () {
      const params = {}
      this.queryDataByPage(params)
    },
    // 表格变动分页查询
    tableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.queryDataByPage(this.searchForm)
      // 查询接口
    },
    // 重置
    resetList () {
      this.pagination.current = 1
      this.$refs.searchForm.resetFields()
      this.queryListByPage()
    },
    // 条件查询
    queryListBycondition () {
      this.pagination.current = 1
      this.queryDataByPage(this.searchForm)
    },
    // 选中行
    selectedRowChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 切换查询区域
    areaChange (value) {
    },
    displayRender ({
      labels
    }) {
      return labels[labels.length - 1]
    },
    // 批量导入
    async batchExport (file) {
      const isExcel =
        file.type === 'application/xlsx' ||
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt2M = file.size / 1024 / 1024 <= 10
      if (!isExcel) {
        this.$message.error('仅支持Excel格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('大小不能超过 10M!')
        return false
      }
      const formData = new FormData()
      formData.append('file', file)
      const url = 'http://www.yunids.com:8082'
      const requestConfig = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.upLoading = true
      await post(url, formData, requestConfig).then((res) => {
        if (res.code === '0') {
          this.$message.success('导入成功!')
        }
      }).catch(() => {
      })
      this.upLoading = false
    },
    // 导出
    importData () {
      let url = ''
      if (process.env.NODE_ENV === 'development') {
        const source = 'http://www.yunids.com:8082'
        url = `${source}`
      } else {
        url = window.location.origin +
          process.env.VUE_APP_BASE_API + '1'
      }
      window.open(url)
    },
    // 提交新增编辑数据
    submitData (data) {
      this.confirmLoading = true
      data.workshopId = data.workshopId || ''
      if (this.optType === 'add') {
        addWorkshop(data).then(res => {
          this.confirmLoading = false
          if (res.code === '0') {
            this.operateVisible = false
            this.$message.success('新增成功!')
            this.resetList()
          }
        }).catch(() => {
          this.confirmLoading = false
        })
      } else {
        updateWorkshop(data).then(res => {
          this.confirmLoading = false
          if (res.code === '0') {
            this.operateVisible = false
            this.$message.success('编辑成功!')
            this.queryDataByPage(this.searchForm)
          }
        }).catch(() => {
          this.confirmLoading = false
        })
      }
    },
    handleOperateTableVisible (data) {
      this.operateVisible = false
    },
    // 新增
    addEquipmentManagement () {
      this.optType = 'add'
      this.operateData = Object.assign({}, {
        workshopId: this.currSelTreeNode.workshopId,
        equipmentType: '1',
        polluteType: '1',
        entinfoId: this.currSelTreeNode.entinfoId,
        name: this.currSelTreeNode.entinfoName,
        equipmentName: '',
        equipmentId: '',
        threshold: '',
        id: ''
      })
      this.operateVisible = true
    },
    // 编辑数据
    editData (text, record, index) {
      this.optType = 'edit'
      this.operateData = Object.assign({}, { id: record.id })
      this.operateData.equipmentType = this.operateData.equipmentType || '1'
      this.operateData.polluteType = this.operateData.polluteType || '1'
      this.operateVisible = true
    },
    // 查看数据
    viewData (text, record, index) {
      this.optType = 'view'
      this.operateData = Object.assign({}, { id: record.id })
      this.operateVisible = true
    },
    // 删除数据
    delData (text, record, index) {
      this.$confirm({
        title: '删除之后无法恢复，确定要删除数据吗?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          const params = {
            id: record.id
          }
          deleteWorkshop(params).then(res => {
            if (res.code === '0') {
              this.$message.success('删除成功!')
              this.pagination.current = getFinalPageNo(
                this.pagination.total,
                this.pagination.current,
                this.pagination.pageSize,
                1)
              this.queryDataByPage(this.searchForm)
            }
          }).catch(() => {
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.equipmentManagement {
  width: 100%;
  height: 100%;
  display: flex;
  .equipmentManagement-tree {
    min-width: 256px;
    background-color: #ffffff;
    margin-right: 20px;
    padding: 20px;
    box-sizing: border-box;
    .tree-content {
      height: 95%;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }
  .table-list {
    background-color: #ffffff;
    padding: 20px;
    box-sizing: border-box;
    overflow-y: auto;
  }
  .tree-custom-item {
    margin-left: 10px;
  }
  .tree-spin > div > .ant-spin {
    top: 300px;
  }
}
</style>
